﻿package com.sochinchou.res.utils;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import android.util.Log;

public class HttpImpl{
	
	private static final String TAG = "=== HttpUtils ===";
	private static final String RET_NETWORK_ERROR = "network_error";
	private static final int DEFAULT_TIME_OUT = 10 * 1000;
	
	public static String httpPost(String strUrl, HashMap<String, String> mapParams) {

		String strResult = RET_NETWORK_ERROR;
		
		HttpClient httpClient = null;
		HttpPost httpPost = null;
		HttpResponse httpResponse = null;
				
					
		try {
			httpClient = new DefaultHttpClient();
			httpPost = new HttpPost(strUrl);
			
			if(mapParams != null){
				List<NameValuePair> valuePairs = new ArrayList<NameValuePair>();
				
				for(String key : mapParams.keySet()){
					valuePairs.add(new BasicNameValuePair(key, mapParams.get(key)));
				}
				
				httpPost.setEntity(new UrlEncodedFormEntity(valuePairs, "gb2312"));
			}
					
			httpResponse = httpClient.execute(httpPost);
			
			if(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
				HttpEntity entity = httpResponse.getEntity();
				if(entity != null)
					strResult = EntityUtils.toString(entity);
			}
			
		} catch (UnsupportedEncodingException e) {
			Log.d(TAG, "UnsupportedEncodingException() >>> " + e.toString());
			return RET_NETWORK_ERROR;
		} catch (ClientProtocolException e) {
			Log.d(TAG, "ClientProtocolException() >>> " + e.toString());
			return RET_NETWORK_ERROR;
		} catch (ParseException e) {
			Log.d(TAG, "ParseException() >>> " + e.toString());
			return RET_NETWORK_ERROR;
		} catch (IOException e) {
			Log.d(TAG, "IOException() >>> " + e.toString());
			return RET_NETWORK_ERROR;
		}
		
		return strResult;	
	}

	
	public static String httpGet(String strUrl, HashMap<String, String> mapParams) {
		String strResult = RET_NETWORK_ERROR;
		
		HttpClient httpClient = null;
		HttpGet httpGet = null;
		HttpResponse httpResponse = null;	
		String url = null;
		
	
		try {
			
			if (mapParams != null) {
				StringBuilder sbParam = new StringBuilder();
				for (String key : mapParams.keySet())
					sbParam.append("&").append(key).append("=").append(mapParams.get(key));
				sbParam.deleteCharAt(0);
				url = strUrl + "?" + sbParam.toString();//
			} else {
				url = strUrl;
			}
			
			httpGet = new HttpGet(url);
			httpClient = new DefaultHttpClient();
			httpResponse = httpClient.execute(httpGet);
			
			if(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
				HttpEntity entity = httpResponse.getEntity();
				if(entity != null)
					strResult = EntityUtils.toString(entity);
			}
			
		} catch (ClientProtocolException e) {
			Log.d(TAG, "ClientProtocolException() >>>" + e.toString());
			return RET_NETWORK_ERROR;
		}  catch (ParseException e) {
			Log.d(TAG, "ParseException() >>> " + e.toString());
			return RET_NETWORK_ERROR;
		} catch (IOException e) {
			Log.d(TAG, "IOException() >>>" + e.toString());
			return RET_NETWORK_ERROR;
		}
		
		return strResult;
	}
	
	
	public static String httpPost2(String strUrl, HashMap<String, String> mapParams){
		URL url = null;
		BufferedReader br = null;
		StringBuilder sbResult = null;
		HttpURLConnection httpConn = null;
		String strResult = RET_NETWORK_ERROR;
		
		try {					
			url = new URL(strUrl);
			Log.d(TAG, "httpPost() >>>>> URL = " + strUrl);
			httpConn = (HttpURLConnection)url.openConnection();
			httpConn.setDoInput(true);
			httpConn.setDoOutput(true);
			httpConn.setConnectTimeout(DEFAULT_TIME_OUT);
			httpConn.setReadTimeout(DEFAULT_TIME_OUT);
			httpConn.setRequestMethod("POST");
			httpConn.connect();
			
			StringBuilder sbParam = new StringBuilder();
			if (mapParams != null) {
				for (String key : mapParams.keySet()) 
					sbParam.append("&").append(key).append("=").append(mapParams.get(key));				
				sbParam.deleteCharAt(0);
			}
			
			PrintWriter out = new PrintWriter(httpConn.getOutputStream());
			out.print(sbParam.toString());
			out.close();
			
			if(httpConn.getResponseCode() == HttpURLConnection.HTTP_OK){
				sbResult = new StringBuilder();
				br = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "UTF-8"));
				String line = null;
				while((line = br.readLine()) != null)
					sbResult.append(line).append("\n");

				strResult = sbResult.toString();
			}else{
				strResult = RET_NETWORK_ERROR;
			}
						
		} catch (MalformedURLException e) {
			Log.d(TAG, "httpPost() >>>>> MalformedURLException");
			return RET_NETWORK_ERROR;
		} catch (IOException e) {
			Log.d(TAG, "httpPost() >>>>> IOException");
			return RET_NETWORK_ERROR;
		}finally{
			
			try{
				if (br != null) 
					br.close();				
				if (httpConn != null) 
					httpConn.disconnect();				
			}catch(IOException e){
				Log.d(TAG, "httpPost() >>>>> close failed.");
			}
		}
		
		return strResult;		
	}
	
		
	public static String httpGet2(String strUrl, HashMap<String, String> mapParams) {

		URL url = null;
		BufferedReader br = null;
		StringBuilder sbResult = null;
		HttpURLConnection httpConn = null;
		String strResult = RET_NETWORK_ERROR;
						
		try {
			
			if (mapParams != null) {
				StringBuilder sbParam = new StringBuilder();
				for (String key : mapParams.keySet()) 
					sbParam.append("&").append(key).append("=").append(mapParams.get(key));				
				sbParam.deleteCharAt(0);
				 url = new URL(strUrl + "?" + sbParam.toString());//		 
			}else{
				 url = new URL(strUrl); 
			}

			Log.d(TAG, "httpGet() >>>>> URL = " + strUrl);
			
			httpConn = (HttpURLConnection) url.openConnection();			
			httpConn.setConnectTimeout(DEFAULT_TIME_OUT);
			httpConn.setReadTimeout(DEFAULT_TIME_OUT);
			httpConn.connect();
			

			if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
				sbResult = new StringBuilder();
				br = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "UTF-8"));
				String line = "";
				while ((line = br.readLine()) != null) 
					sbResult.append(line).append("\n");				
				strResult = sbResult.toString();				
			} else {
				strResult =  RET_NETWORK_ERROR;
			}
			
		} catch (MalformedURLException e) {
			Log.d(TAG, "httpGet() >>>>> MalformedURLException");
			return RET_NETWORK_ERROR;
		}catch (IOException e) {
			Log.d(TAG, "httpGet() >>>>> IOException");
			return RET_NETWORK_ERROR;
		}finally {

			try{
				if (br != null) 
					br.close();				
				if (httpConn != null) 
					httpConn.disconnect();				
			}catch(IOException e){
				Log.d(TAG, "httpGet() >>>>> close failed.");
			}
		}

		return strResult;
	}
	
	
    public static String fileUpload(String strUrl, Map<String, String> mapParams, File file){  
    	
		URL url = null;
		BufferedReader br = null;
		DataOutputStream outStream = null;
		HttpURLConnection httpConn = null;		
		StringBuilder sbResult = null;
		String strResult = RET_NETWORK_ERROR;
		
        String BOUNDARY = UUID.randomUUID().toString();  
        String PREFIX = "--";
        String LINEND = "\r\n";  
        String MULTIPART_FROM_DATA = "multipart/form-data";  
        String CHARSET = "UTF-8";  
        
        try{
            url = new URL(strUrl);
            Log.d(TAG, "fileUpload() >>>>> url = " + url);
            httpConn = (HttpURLConnection) url.openConnection();  
            httpConn.setReadTimeout(10 * 1000);  
            httpConn.setConnectTimeout(10 * 1000);
            httpConn.setDoInput(true);// ��������  
            httpConn.setDoOutput(true);// �������  
            httpConn.setUseCaches(false);  
            httpConn.setRequestMethod("POST"); // Post��ʽ 
            
            httpConn.setRequestProperty("Connection", "close");  
            httpConn.setRequestProperty("Accept-Charsert", "UTF-8");  
            httpConn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA  + ";boundary=" + BOUNDARY);  
            
            outStream = new DataOutputStream( httpConn.getOutputStream());  
            
            // ���Ͳ������ 
            if(mapParams != null){
                StringBuilder sb1 = new StringBuilder();  
                for (Map.Entry<String, String> entry : mapParams.entrySet()) {  
                    sb1.append(PREFIX + BOUNDARY + LINEND);  
                    sb1.append("Content-Disposition: form-data; name=\""  + entry.getKey() + "\"" + LINEND);  
//                    sb1.append("Content-Type: text/plain; charset=" + CHARSET + LINEND);  
//                    sb1.append("Content-Transfer-Encoding: 8bit" + LINEND);                     
                    sb1.append(LINEND);                 
                    sb1.append(entry.getValue() + LINEND);  
                }        
                outStream.writeBytes(sb1.toString());  
            }
            
            // �����ļ����  
            if(file != null){
            	StringBuilder sb2 = new StringBuilder();  
                sb2.append(PREFIX + BOUNDARY + LINEND);  
                sb2.append("Content-Disposition: form-data; name=\"file\"; filename=\""  + file.getName() + "\"" + LINEND);  
                sb2.append("Content-Type: application/octet-stream; charset="  + CHARSET + LINEND);                 
                sb2.append(LINEND);   // start output
                outStream.writeBytes(sb2.toString());  
                
                FileInputStream is = new FileInputStream(file);  
                byte[] buffer = new byte[1024];  
                int len = 0;  
                while ((len = is.read(buffer)) != -1) {  
                    outStream.write(buffer, 0, len);  
                }  
                is.close();  
                outStream.writeBytes(LINEND);  //end output
            }
            // ��������־   
            outStream.writeBytes(PREFIX + BOUNDARY + PREFIX + LINEND); 
            outStream.flush();  
            
            // �õ���Ӧ��  
    		if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
    			sbResult = new StringBuilder();
    			br = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "UTF-8"));
    			String line = "";
    			while ((line = br.readLine()) != null) 
    				sbResult.append(line).append("\n");				
    			strResult = sbResult.toString();				
    		} else {
    			strResult =  RET_NETWORK_ERROR;
    		}
    		       
            return strResult;
            
        }catch (MalformedURLException e) {
			Log.d(TAG, "fileUpload() >>>>> MalformedURLException");
			return RET_NETWORK_ERROR;
		}catch (IOException e) {
			Log.d(TAG, "fileUpload() >>>>> IOException");
			return RET_NETWORK_ERROR;
		}finally{
			try{
				if(outStream != null)
					outStream.close();
				if (br != null) 
					br.close();				
				if (httpConn != null) 
					httpConn.disconnect();				
			}catch(IOException e){
				Log.d(TAG, "fileUpload() >>>>> close failed.");
			}
		}       
    } 
	
    
    public static String fileMultiUpload(String strUrl, Map<String, String> mapParams, Map<String, File> filesMap){  
    	
		URL url = null;
		BufferedReader br = null;
		DataOutputStream outStream = null;
		HttpURLConnection httpConn = null;		
		StringBuilder sbResult = null;
		String strResult = RET_NETWORK_ERROR;
		
        String BOUNDARY = UUID.randomUUID().toString();  
        String PREFIX = "--";
        String LINEND = "\r\n";  
        String MULTIPART_FROM_DATA = "multipart/form-data";  
        String CHARSET = "UTF-8";  
        
        try{
            url = new URL(strUrl);  
            Log.d(TAG, "fileMultiUpload() >>>>> url = " + url);
            httpConn = (HttpURLConnection) url.openConnection();  
            httpConn.setReadTimeout(10 * 1000);  
            httpConn.setConnectTimeout(10 * 1000);
            httpConn.setDoInput(true);// ��������  
            httpConn.setDoOutput(true);// �������  
            httpConn.setUseCaches(false);  
            httpConn.setRequestMethod("POST"); // Post��ʽ 
            
            httpConn.setRequestProperty("Connection", "close");  
            httpConn.setRequestProperty("Accept-Charsert", "UTF-8");  
            httpConn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA  + ";boundary=" + BOUNDARY);  
            
            outStream = new DataOutputStream( httpConn.getOutputStream());  
            
            // ���Ͳ������ 
            if(mapParams != null){
                StringBuilder sb1 = new StringBuilder();  
                for (Map.Entry<String, String> entry : mapParams.entrySet()) {  
                    sb1.append(PREFIX + BOUNDARY + LINEND);  
                    sb1.append("Content-Disposition: form-data; name=\""  + entry.getKey() + "\"" + LINEND);  
//                    sb1.append("Content-Type: text/plain; charset=" + CHARSET + LINEND);  
//                    sb1.append("Content-Transfer-Encoding: 8bit" + LINEND);                      
                    sb1.append(LINEND);                 
                    sb1.append(entry.getValue() + LINEND);  
                }        
                outStream.writeBytes(sb1.toString());  
            }
            
          //�����ļ����
            if (filesMap != null){  
                for (Map.Entry<String, File> file : filesMap.entrySet()) {  
                    StringBuilder sb2 = new StringBuilder();  
                    sb2.append(PREFIX + BOUNDARY + LINEND);  
                    sb2.append("Content-Disposition: form-data; name=\"file\"; filename=\""  + file.getKey() + "\"" + LINEND);  
                    sb2.append("Content-Type: application/octet-stream; charset="  + CHARSET + LINEND);                      
                    sb2.append(LINEND);  // start output
                    outStream.writeBytes(sb2.toString()); 
                    
                    InputStream is = new FileInputStream(file.getValue());  
                    byte[] buffer = new byte[1024];  
                    int len = 0;  
                    while ((len = is.read(buffer)) != -1) {  
                        outStream.write(buffer, 0, len);  
                    }  
                    is.close();  
                    outStream.writeBytes(LINEND);  //end output
                }  
            }
            // ��������־   
            outStream.writeBytes(PREFIX + BOUNDARY + PREFIX + LINEND); 
            outStream.flush();  
            
            // �õ���Ӧ��  
    		if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
    			sbResult = new StringBuilder();
    			br = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "UTF-8"));
    			String line = "";
    			while ((line = br.readLine()) != null) 
    				sbResult.append(line).append("\n");				
    			strResult = sbResult.toString();				
    		} else {
    			strResult =  RET_NETWORK_ERROR;
    		}
    		       
            return strResult;
            
        }catch (MalformedURLException e) {
			Log.d(TAG, "fileUpload() >>>>> MalformedURLException");
			return RET_NETWORK_ERROR;
		}catch (IOException e) {
			Log.d(TAG, "fileUpload() >>>>> IOException");
			return RET_NETWORK_ERROR;
		}finally{
			try{
				if(outStream != null)
					outStream.close();
				if (br != null) 
					br.close();				
				if (httpConn != null) 
					httpConn.disconnect();				
			}catch(IOException e){
				Log.d(TAG, "fileUpload() >>>>> close failed.");
			}
		}       
    }     
}